package cn.itcast.controller.system;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.system.Dept;
import cn.itcast.service.system.DeptService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.UUID;

@RequestMapping("/system/dept")
@Controller
public class DeptController extends BaseController{
    @Autowired
    private DeptService deptService;
    @RequestMapping(value = "/list",name = "分页查询所有的部门")
    public String findAll(@RequestParam(name = "page",defaultValue = "1")int pageNum,@RequestParam(defaultValue = "5")int pages){
        PageInfo<Dept> pageInfo = deptService.findPages(getCompanyId(), pageNum, pages);
        request.setAttribute("page",pageInfo);
        return "system/dept/dept-list";
    }
    @RequestMapping(value = "/toAdd",name = "跳转到添加部门界面")
    public String add(){
        List<Dept> list = deptService.findAllById(getCompanyId());
        request.setAttribute("deptList",list);
        return "system/dept/dept-add";
    }
    @RequestMapping(value = "/edit",name = "添加部门界面")
    public String insert(Dept dept){
        //若dept的id值是空的，则证明是从添加界面来的
        if(StringUtils.isBlank(dept.getId())){
        dept.setId(UUID.randomUUID().toString());
        dept.setCompanyId(getCompanyId());
        dept.setCompanyName(getCompanyName());
        if(StringUtils.isBlank(dept.getParent().getId())){
            dept.getParent().setId(null);
        }
        deptService.insert(dept);
        }else {
            //否则则是从修改界面来的
            dept.setCompanyName(getCompanyName());
            dept.setCompanyId(getCompanyId());
            if(StringUtils.isBlank(dept.getParent().getId())){
                dept.setParent(null);
            }
            System.out.println(dept);
            deptService.update(dept);
        }
        return "redirect:/system/dept/list.do";
    }
    @RequestMapping(value = "/delete",name = "删除选中的部门")
    public String delete(String id){
        deptService.deleteById(id);
        return "redirect:/system/dept/list.do";
    }
    @RequestMapping(value = "/toUpdate",name = "进入到修改部门界面")
    public String toUpdate(String id){
        List<Dept> list = deptService.findAllById(getCompanyId());
        request.setAttribute("deptList",list);
        Dept dept=deptService.findById(id);
        request.setAttribute("dept",dept);
        return "system/dept/dept-add";
    }
}
